<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="warning" @click="showAddDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <zk-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === true"
            style="color: lightgreen"
          >
          </i>
          <i class="el-icon-error" v-else style="color: red"> </i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="showDeleteDialog"
          >
            删除
          </el-button>
        </template>
      </zk-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 提交分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        ref="addCateFormRef"
        :model="addCateForm"
        label-width="80px"
        :rules="addCatFormRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCatList"
            @change="parentCateChanged"
            :props="cascaderProps"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品分类的对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClosed"
    >
      <el-form
        ref="editCateFormRef"
        :model="editCateForm"
        label-width="80px"
        :rules="editCatFormRules"
      >
        <el-form-item label="新的分类名称" prop="cat_name" label-width="120px">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="分类名称" label-width="120px">
          <el-cascader
            v-model="selectedEditKeys"
            :options="editCatList"
            @change="editCateChanged"
            :props="cascaderEditProps"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除商品分类的对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="deleteCateDialogVisible"
      width="50%"
      @close="deleteCateDialogClosed"
    >
      <el-form
        ref="deleteCateFormRef"
        :model="deleteCateForm"
        label-width="80px"
      >
        <el-form-item label="分类名称" label-width="120px">
          <el-cascader
            v-model="selectedDeleteKeys"
            :options="deleteCatList"
            @change="deleteCateChanged"
            :props="cascaderdeleteProps"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteCate">删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询条件
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类的数据列表
      cateList: [],
      // 总数据条数
      total: 0,
      //添加分类的表单数据对象
      addCateForm: { cat_name: "", cat_pid: 0, cat_level: 0 },
      // 编辑分类的表单数据
      editCateForm: { cat_name: "", cat_id: 0 },
      // 删除分类的数据表单
      deleteCateForm: { cat_id: 0 },
      // 编辑商品分类列表
      editCatList: [],
      //父级商品分类的列表
      parentCatList: [],
      // 删除商品分类的列表
      deleteCatList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        chlidren: "chlidren",
      },
      // 指定级联选择器的配置对象
      cascaderEditProps: {
        value: "cat_id",
        label: "cat_name",
        chlidren: "chlidren",
      },
      // 指定级联选择器的配置对象
      cascaderdeleteProps: {
        value: "cat_id",
        label: "cat_name",
        chlidren: "chlidren",
      },
      //选中了的父级分类的id数组
      selectedKeys: [],
      // 选择要编辑的id数组
      selectedEditKeys: [],
      // 选择删除的id数组git
      selectedDeleteKeys: [],
      //添加商品分类的规则
      addCatFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        cat_level: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //编辑商品分类的规则
      editCatFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // vue-table-tree-grid ：为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      // 控制添加商品分类对话框的打开与关闭
      addCateDialogVisible: false,
      // 控制编辑商品分类对话框的打开与关闭
      editCateDialogVisible: false,
      // 控制删除商品分类对话框的打开与关闭
      deleteCateDialogVisible: false,
    };
  },
  created() {
    // 获取商品分类数据
    this.getCateList();
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.querInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品数据失败");
      // console.log(res.data);
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 监听newsize的变化
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.querInfo.pagesize = newSize;
      this.getCateList();
    },
    // 监听页码发生的变化
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.querInfo.pagenum = newPage;
      this.getCateList();
    },
    // 点击打开分配商品类型的对对话框
    showAddDialog() {
      //获取父级数据列表
      this.getParentCateList();
      //展示对话框
      this.addCateDialogVisible = true;
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: {
          type: 2,
        },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级商品分类失败");
      this.$message.success("获取父级商品数据列表成功");
      this.parentCatList = res.data;
    },
    // 选择项发生变化时触发该函数
    parentCateChanged() {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        this.addCateForm.cat_level = this.selectedKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    // 点击添加分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        this.getCateList;
        this.addCateDialogVisible = false;
      });
    },
    // 分配商品分类的对话框的关闭事件函数
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    // 展示编辑商品分类对话框
    showEditDialog() {
      this.editCateDialogVisible = true;
      this.getAllCateList();
    },
    // 分配商品分类的关闭函数
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields();
      this.selectedEditKeys = [];
      this.editCateForm.cat_id = 0;
      this.editCateForm.cat_name = "";
    },
    // 点击按钮提交编辑数据
    editCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.editCateForm.cat_id}`,
          { cat_name: this.editCateForm.cat_name }
        );
        if (res.meta.status !== 200) return this.$message.error("编辑失败");
        this.$message.success("编辑成功");
        this.getCateList();
        this.editCateDialogVisible = false;
      });
    },
    // 选择发生变化时触发该函数
    async editCateChanged() {
      if (this.selectedEditKeys.length > 0) {
        this.editCateForm.cat_id =
          this.selectedEditKeys[this.selectedEditKeys.length - 1];
        const { data: res } = await this.$http.get(`categories/${
          this.selectedEditKeys[this.selectedEditKeys.length - 1]
        };
}`);
        if (res.meta.status !== 200)
          return this.$message.error("获取商品分类失败");
        // console.log(res);
        this.editCateForm.cat_name = res.data.cat_name;
      } else {
        this.editCateForm.cat_id = 0;
        this.editCateForm.cat_name = "";
      }
    },
    //获取所有商品列表
    async getAllCateList() {
      const { data: res } = await this.$http.get("categories", { type: 3 });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品数据失败");
      this.editCatList = res.data;
      this.deleteCatList = res.data;
      // console.log(this.editCatList);
    },
    // 展示删除对话框
    showDeleteDialog() {
      this.deleteCateDialogVisible = true;
      this.getAllCateList();
    },
    // 删除对话框的关闭函数
    deleteCateDialogClosed() {
      this.$refs.deleteCateFormRef.resetFields();
      this.selectedDeleteKeys = [];
      this.deleteCateForm.cat_id = 0;
      this.deleteCateDialogVisible = false;
    },
    // 发生变化时触发该函数
    deleteCateChanged() {
      if (this.selectedDeleteKeys.length > 0) {
        this.deleteCateForm.cat_id =
          this.selectedDeleteKeys[this.selectedDeleteKeys.length - 1];
      } else {
        this.editCateForm.cat_id = 0;
      }
    },
    // 点击按钮删除分类
    deleteCate() {
      this.$refs.deleteCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.delete(
          `categories/${this.deleteCateForm.cat_id}`
        );
        if (res.meta.status !== 200) return this.$message.error("删除失败");
        this.$message.success("删除成功");
        this.getCateList();
        this.deleteCateDialogVisible = false;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 15px;
}
</style>
